<template>
    <div class="logistics-management">
      <!-- 顶部按钮组 -->

      <el-button-group>
        <el-button  @click="batchDel">批量取消调度</el-button>
        <el-button>导入</el-button>
        <el-button plain @click="exportExcel">导出</el-button>
        <el-button>打印</el-button>
      </el-button-group>

       <!-- 状态标签 -->
       <el-tabs v-model="searchForm.status"  @tab-click="onSearch"> <!--  -->
          <el-tab-pane label="全部" name=""></el-tab-pane>
          <el-tab-pane label="待接单" name="1"></el-tab-pane>
          <el-tab-pane label="待提货" name="2"></el-tab-pane>
          <el-tab-pane label="待发车" name="3"></el-tab-pane>
          <el-tab-pane label="运输中" name="4"></el-tab-pane>
          <el-tab-pane label="待签收" name="5"></el-tab-pane>
          <el-tab-pane label="已完成" name="6"></el-tab-pane>
          <el-tab-pane label="已取消" name="7"></el-tab-pane>
        </el-tabs>
      <!-- 搜索栏 -->
      <el-form :inline="true"  class="demo-form-inline">    <!-- :model="searchForm" -->
      
        
        <el-form-item label="始发地" >
          <el-cascader v-model="searchForm.originList"
            :options="originOptions"
            :props="props"
            clearable
            placeholder="请选择始发地">
          </el-cascader>
        </el-form-item>
        <el-form-item label="目的地" >
     
          <el-cascader v-model="searchForm.destinationList"
            :options="originOptions"
            :props="props"
            clearable
            placeholder="请选择始发地">
          </el-cascader>
        </el-form-item>
        <el-form-item label="运输方式">
          <el-select placeholder="请选择" clearable v-model="searchForm.transportId" ><!-- v-model="searchForm.transportId" -->
            <el-option
                v-for="transport in transports"
                :key="transport.id"
                :label="transport.transportName"
                :value="transport.id"
                >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
           <!-- v-model="searchForm.orderCreatedTimeList" -->
          <el-date-picker   
           v-model="searchForm.orderCreatedTimeList"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input  placeholder="请输入关键词搜索" clearable v-model="searchForm.keyword" ></el-input> <!--  -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" 
      @selection-change="handSelectionChange"
      style="width: 100%"
      >
       <!--           多选按钮                 -->
        <el-table-column type="selection" >
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
            <el-button size="mini" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="mini" @click="handleDispatch(scope.row)">分配承运商</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">取消调度</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="运单号" width="200px">
          <template slot-scope="scope">
        <el-link 
          type="primary" 
          @click="handleDetail(scope.row)"
        >
          {{ scope.row.id }}
        </el-link>
      </template>
        </el-table-column>
        <el-table-column label="始发地" width="130px">
          <template slot-scope="scope">
            <div>
           <span>{{ scope.row.name1 }}</span>/
           <span> {{ scope.row.name2 }}</span> 
            </div>
            </template>
        </el-table-column>
        <el-table-column label="目的地" width="180px" >
          <template slot-scope="scope">
            <div>
           <span>{{ scope.row.name3 }}</span>/
           <span> {{ scope.row.name4 }}</span> 
            </div>
            </template>
        </el-table-column>

        <el-table-column prop="status" label="运单状态">
              <template slot-scope="scope">
                    {{scope.row.status == 1?'待接单':
                    (scope.row.status == 2?'待提货':
                    (scope.row.status == 3?'待发车':
                    (scope.row.status == 4?'运输中':
                    (scope.row.status == 5?'待签收':
                    (scope.row.status == 6?'已完成':
                    (scope.row.status == 7?'已取消':''))))))}}
                  </template>
        </el-table-column>

        <el-table-column prop="transportName" label="运输方式"></el-table-column>
        <el-table-column prop="companyName" label="承运商" width="130px"></el-table-column>
        <el-table-column prop="name" label="司机"></el-table-column>
        <el-table-column prop="contact" label="手机号码"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌"></el-table-column>
        <el-table-column prop="vehicleType" label="车型"></el-table-column>
        <el-table-column prop="vehicleLength" label="车长"></el-table-column>
        <el-table-column prop="billingMethod" label="计费方式" width="130px">
          <template slot-scope="scope">
              {{scope.row.billingMethod == 0?'按重量计算':(scope.row.billingMethod == 1?'按体积计算':'')}}
          </template>
        </el-table-column>
        <el-table-column prop="totalFee" label="运费合计（元）"  width="130px"></el-table-column>
        <el-table-column prop="planDepartureTime" label="计划发车时间" width="150px"></el-table-column>
        <el-table-column prop="actualDepartureTime" label="实际发车时间"  width="150px"></el-table-column>
        <el-table-column prop="planArrivalTime" label="计划到达时间"  width="150px"></el-table-column>
        <el-table-column prop="actualArrivalTime" label="实际到达时间"  width="150px"></el-table-column>
        <el-table-column prop="orderCreatedTime" label="接单时间" width="150px"></el-table-column>
        <el-table-column prop="orderCreatedTime" label="下单时间" width="150px"></el-table-column>
        <el-table-column prop="realName" label="创建人"></el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="150px"></el-table-column>
        
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
          background
          :page-sizes="[3, 5, 7,10, 20]"
          :page-size="pageSize"
          :current-page="pageNum"
          layout=" total,sizes,prev, pager, next,jumper"
          :total="total"
          @next-click="nextPage"
          @prev-click="prevPage"
          @current-change="changePage"
          @size-change="sizeChange">
      </el-pagination>
    </div>
  </template>
  
  <script>
  export default {
    name: 'LogisticsManagement',
    data() {
      return {
        searchForm: {
          status:'',
          // keyword:'',
          // originId: [],
        },

        originOptions: [ ],
        props: { value:'id',label:'name',children:'cityList' },  //配置级联选择器多选
        tableData: [], // 这里需要填充实际的数据
        pageSize: 7,
        multilpeSelection:[],
        total: 0,
        pageNum:1,
        transports:[], //地址数组
      }
    },
    methods: {
      handSelectionChange(val){
                //点击复选框事件  val :是选中的对象数组
                console.log(val)
                 this.multilpeSelection= val ;
            },
      batchDel(){
        let ids = this.multilpeSelection.map(e =>e.id);
          this.$confirm('批量取消调度?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
            this.$axios.post("/api/waybill/batchDel",ids)
              .then(resp =>{
                  console.log(resp.data)
                  if(resp.data.code===200){
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.onSearch();
                  } 
                  if(resp.data.code===2001){
                    this.$message({
                        type: 'success',
                        message: '操作失败，有运单不能取消调度!'
                    });
                  }      
              })
              .catch(error => {
                    console.error('操作失败:', error);
                    this.$message.error('网络请求失败，请稍后再试');
                });
          }).catch(() => {
              this.$message({
                  type: 'info',
                  message: '已取消批量操作'
              });
          });
      },
      onSearch() {
        // 实现搜索逻辑
        let pageParam = {};
        pageParam.pageNum = this.pageNum;
        pageParam.pageSize = this.pageSize;
        pageParam.param = this.searchForm;
        this.$axios.post("/api/waybill/queryWaybill",pageParam)
            .then(resp =>{
              console.log(resp.data)
              if(resp.data.code==200){
                //给数据tableData赋值
                this.tableData =resp.data.data.list
                //给分页总数赋值
                this.total = resp.data.data.total
            }
            })
      },
      queryOrigin(){
        //查询所有始发地
        this.$axios.get("/api/provincial/queryProvincial")
            .then(resp =>{
              console.log(resp.data)
              if(resp.data.code==200){
                this.originOptions = resp.data.data
              }
            })
      },
      queryTransport(){
          //查询运输方式所有
          this.$axios.get("/api/waybill/queryTransport")
            .then(resp =>{
              console.log(resp.data)
              if(resp.data.code==200){
                this.transports = resp.data.data
              }
            })
      },
      onReset() {
        // 重置搜索表单
        this.searchForm = {
          status:'',
        }
        this.onSearch()
      },

      handleDetail(val) {
        // 查看详情操作
         // 将整行数据存储到 localStorage
        // localStorage.setItem('waybillDetails', JSON.stringify(row));
        // 导航到详情页面，只传递 ID
        this.$router.push({ path: '/details', query: { 'waybillId': val.id } })
         // 导航到详情页面，只传递 ID
        // this.$router.push({ name: 'WaybillDetail', params: { id: row.id } });
      },
      handleDispatch(val){
        // 再发一个请求判断当前状态，是否可以继续分配承运商
        this.$axios.get("/api/waybill/judgment/"+val.id)
          .then(resp=>{
                console.log(resp.data);
                if (resp.data.code ===2015){
                    this.$message({
                        type: 'success',
                        message: '无法修改承运商!'
                    });
                }
                if (resp.data.code ===200){
               // 导航到派遣页面，传递 ID
                this.$router.push({ path: '/dispatch', query: { 'waybillId': val.id } })
              }
            })
    
      },
      handleDelete(row) {
        // 处理取消调度操作
        this.$confirm('是否取消承运商司机绑定?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                  //发送请求
                  // let param = {}
                  // param.id=row.id
                  // param.status=row.status
                  this.$axios.get("/api/waybill/Cancel/"+row.id)
                        .then(resp =>{
                            if (resp.data.code ===200){
                                console.log(this.data)
                                this.$message({
                                    type: 'success',
                                    message: '解绑成功!'
                                });
                               this.onSearch()
                            }
                            if (resp.data.code ===2001){
                                console.log(this.data)
                                this.$message({
                                    type: 'info',
                                    message: '司机已提货，不能解绑!'
                                });
                            }
                            if (resp.data.code ===2003){
                                console.log(this.data)
                                this.$message({
                                    type: 'info',
                                    message: '没绑定，请绑定承运商'
                                });
                            }
                        })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消解绑'
                    });
                });
      },
      /**
         * 导出
         */
         exportExcel() {

          // 使用 axios 获取文件流
          this.$axios({
              url: '/api/waybill/export',
              method: 'GET',
              responseType: 'blob',  // 指定响应类型为 blob
          }).then(response => {
              // 创建 Blob 对象
              const blob = response.data;

              // 创建一个 URL 对象来表示该 Blob
              const url = window.URL.createObjectURL(blob);

              // 创建一个临时的下载链接
              const link = document.createElement('a');
              link.href = url;
              link.download = 'data.xlsx';  // 设置下载的文件名

              // 触发点击事件下载文件
              document.body.appendChild(link);
              link.click();

              // 下载后清理链接
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url); // 释放 Blob URL
          }).catch(error => {
              console.error('导出失败:', error);
          });
          },




      handleSizeChange(val) {
        this.pageSize = val;
        // 重新加载数据
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        // 重新加载数据
      },


    nextPage(val){   //val 当前页 方法自动获取当前页
              //下一页  获取当前页pageNum
              this.pageNum= val;
              this.onSearch();
          },
    prevPage(val){
        //下一页
        this.pageNum= val;
        this.onSearch();
    },
    changePage(val){
        //当前页
        this.pageNum= val;
        this.onSearch();
    },
    sizeChange(val){
        //下拉框  每页条数
        this.pageSize= val;
        this.pageNum=1;
        this.onSearch();
    }

    },
    created() {
      this.onSearch()
      this.queryOrigin()
      this.queryTransport()
    },
  }
  </script>
  
  <style scoped>
  .logistics-management {
    padding: 20px;
  }
  </style>